import { Message } from 'element-ui'
import { heartbeat } from '@/utils/messageUtil'
import { dispatcherServlet } from './dispatcher/dispatcher'

let socket
const address = 'ws://localhost:8080/websocket'

if (!window.WebSocket) {
  window.WebSocket = window.MozWebSocket
}

if (window.WebSocket) {
  socket = new WebSocket(address)

  socket.onmessage = function(event) {
    const obj = JSON.parse(event.data)
    dispatcherServlet(obj)
  }

  socket.onopen = function(event) {
    setInterval(function() {
      heartbeat()
    }, 60000)
  }

  // eslint-disable-next-line no-unused-vars
  socket.onclose = function(event) {
  }
} else {
  Message.error('Your browser does not support Web Socket.')
}

function send(msg) {
  if (!window.WebSocket) {
    return
  }
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(msg)
  } else {
    Message.error('The socket is not open.')
  }
}

export { send }
